const DB = require('../db')

const contentCache = {};

function findCache(content) {
    let cache = contentCache[content.siteId];
    if (!cache) {
        return false;
    }
    return cache.findIndex(item => item.siteId === content.siteId &&
        item.title === content.title &&
        item.keywordId === content.keywordId &&
        item.date === item.date) >= 0;
}

function insertCache(content) {
    let cache = contentCache[content.siteId];
    if (!cache) {
        cache = contentCache[content.siteId] = [];
    }
    if (cache.length > 100) {
        cache.pop();
    }
    cache.push(content);
}


async function save(content) {
    return await new DB.Content(content).save()
}

async function saveContents(contents) {
    let saved = [];
    for (const content of contents) {
        let result = findCache(content);
        if (findCache(content)) {
            continue;
        }
        let contentExist = await DB.Content.findOne({
            siteId: content.siteId,
            keywordId: content.keywordId,
            title: content.title,
            date: content.date
        });
        if (!contentExist) {
            let savedContent = await save(content);
            saved.push(content);
        }
        insertCache(content);
    }
    return saved;
}


async function query(pageNum = 1, pageCount = 10, filter) {
    pageNum = Number(pageNum);
    pageCount = Number(pageCount);
    return await DB.Content
        .find(filter)
        .sort({
            _id: -1
        })
        .limit(pageCount)
        .skip((pageNum - 1) * pageCount)
        .select()
}

async function queryAll() {
    return await DB.Content
        .find({
            state: 1
        })
        .select();
}

async function total() {
    return DB.Content.countDocuments();
}

module.exports = {
    save,
    query,
    saveContents,
    queryAll,
    total
}